const confirmOperateBaseSelectOrForm = function ({ data, model, selection, mustSelection, mustData, callback, }) {

    if (mustSelection) {
        if (_.isEmpty(selection)) {
            return this.$message.error(this.$tt('tip_please_select_entry'))
        }
    }
    if (mustData) {
        if (_.isEmpty(data)) {
            return this.$message.error(this.$tt('tip_search_criteria_no_empty'))
        }
    }
    let option = {}
    if (_.isEmpty(selection)) {
        let dataClone = _.cloneDeep(data)
        let modelClone = _.cloneDeep(model)
        modelClone = modelClone.filter(it => {
            it.render = null
            it.disabled = true
            return dataClone[it.key] != null && dataClone[it.key] != '' && dataClone[it.key] != undefined
        })
        const h = this.$createElement
        let title = this.$tt("tip_is_want_operate_based_on_no_criteria")
        let message = null
        if (!_.isEmpty(modelClone)) {
            title = this.$tt("tip_is_want_operate_based_on_following_criteria")
            message = h("ex_super_form", {
                props: {
                    data: dataClone,
                    model: modelClone,
                    isSupportFold: false,
                    attrs: {
                        inline: true,

                    }
                }
            })
        }
        option = {
            // customClass: "dialog_auto",
            title: title,
            message: message,
            showConfirmButton: true,
            showCancelButton: true,
            callback: (action, instance) => {
                if (action === 'confirm') {
                    callback(selection, data)
                }
            }
        }
    } else {
        option = {
            // customClass: "dialog_auto",
            title: this.$tt("tip_is_want_operate_based_on_select_entry", { count: selection.length }),
            // message: this.$tt("tip_is_want_operate_based_on_select_entry", { count: selection.length }),
            showConfirmButton: true,
            showCancelButton: true,
            callback: (action, instance) => {
                if (action === 'confirm') {
                    callback(selection, data)
                }
            }
        }
    }
    this.$msgbox(option).then(() => { }).catch(() => { });
}

const checkBalanceAndRecharge = function ({ enumValue, success, failure }) {
    if (success && !!enumValue) {
        success()
        return
    }
    this.$ajaxCache({
        url: '/fms-api/client/FmsClientRpc/selectCustomerAccountInfo.json',
        loading: true,
        success: (responseData) => {
            if (responseData.data) {
                if (enumValue && responseData.data.creditAccountList && responseData.data.creditAccountList.some(it => it.productType == enumValue)) {
                    if (success) success()
                } else {
                    const cashSum = _.reduce(responseData.data.cashAccountList, (sum, v) => this.$math_add(sum, Number(v.convertAmount)), 0)
                    if (cashSum > 0) {
                        if (success) success()
                    } else {
                        if (failure) failure()
                        this.$confirm(this.$tt('tip_recharge_account_amount_lack'), this.$tt('label_recharge_tip'), {
                            confirmButtonText: this.$t('label_goto_recharge'),
                            type: 'warning'
                        }).then(() => {
                            this.$router.push({ name: '/page/fms/account/recharge', params: { autoRecharge: true } })
                        }).catch(() => {

                        });
                    }
                }
            }
        },
        failure: () => {
            if (failure) failure()
        }
    });
}
function getPrintConfigLocalStorageKey() {
    let key = 'printConfig'
    if (__LONG_USER__.isCustomerSystem) {
        key += ("?u=" + __LONG_USER__.userId)
    } else if (__LONG_USER__.isWmsSystem) {
        key += ("?w=" + __LONG_USER__.currentWarehouseId)
    } else if (__LONG_USER__.isOmsSystem) {
        key += ("?o=" + __LONG_USER__.currentAgentId)
    }
    return key
}
const clientPrintBussinessEnum = [
    "BIN", "SKU", "PRE_BIN",
]
//读取打印配置
function loadPrintConfig({ typeAll, typeKey, storageKey }) {
    if (storageKey) {
        try {
            return JSON.parse(window.localStorage.getItem(storageKey))
        } catch (e) {
            return []
        }
    }
    if (!typeKey && !typeAll) return null
    let localConfig = window.localStorage.getItem(getPrintConfigLocalStorageKey())
    if (localConfig) {
        try {
            localConfig = JSON.parse(localConfig)


        } catch (e) {
            localConfig = []
        }
    } else {
        localConfig = []
    }

    let templateBaseEnum = __JAVA_ENUM_OPTIONS__["PrintBussinessTypeEnum"] || []
    if (__LONG_USER__.isCustomerSystem) {
        templateBaseEnum = clientPrintBussinessEnum
    }

    const templateBaseItems = (templateBaseEnum).map(it => {
        return Object.assign({
            key: it,
            clientId: null, printerName: null,
            templateId: null,
        }, _.find(localConfig, { key: it }))
    })
    let OUTBOUND_WAYBILL_Items = []
    if (__LONG_USER__.isWmsSystem) {
        OUTBOUND_WAYBILL_Items = (__JAVA_ENUM_OPTIONS__["OmsOutboundOrderEcPlatformEnum"] || []).map(it => {
            return Object.assign({
                key: it,
                clientId: null, printerName: null,
                templateId: null,
                linkKey: "OUTBOUND_WAYBILL",
                tempPt: ['Wildberries'].includes(it),
                tempForce: ['Wildberries'].includes(it),
            }, _.find(localConfig, { key: it }))
        })
    }
    localConfig = _.concat(templateBaseItems, OUTBOUND_WAYBILL_Items)

    if (typeAll) {
        return localConfig
    }
    const item = _.find(localConfig, { key: typeKey })

    if (item) {
        if (__JAVA_ENUM_OPTIONS__["OmsOutboundOrderEcPlatformEnum"].includes(item.key)) {
            const baseItem = _.find(localConfig, { key: 'OUTBOUND_WAYBILL' })
            if (baseItem) {
                if (!item.clientId) {
                    item.clientId = baseItem.clientId
                    item.printerName = baseItem.printerName
                }
                if (!item.templateId && item.tempPt) {
                    item.templateId = baseItem.templateId
                }
            }
        }
        return [item]

    } else {
        return []
    }
}
//保存打印配置
function savePrintConfig({ data, storageKey }) {
    let saveData = null
    if (_.isArray(data)) {
        saveData = data.map(it => _.pick(it, ['key', 'clientId', 'printerName', 'templateId', 'tempPt']))
    } else {
        saveData = [_.pick(data, ['key', 'clientId', 'printerName', 'templateId', 'tempPt'])]
    }
    if (storageKey) {
        if (_.isEmpty(saveData)) {
            window.localStorage.removeItem(storageKey)
        } else {
            window.localStorage.setItem(storageKey, JSON.stringify(saveData))
        }
        return
    }

    const localConfig = loadPrintConfig({ typeAll: true, storageKey })
    window.localStorage.setItem(getPrintConfigLocalStorageKey(), JSON.stringify(_.unionBy(saveData, localConfig, 'key')))
}
export default {
    confirmOperateBaseSelectOrForm, checkBalanceAndRecharge,
    loadPrintConfig, savePrintConfig,

}
